package com.das.mechanic_base.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3MyApp;
import com.das.mechanic_base.bean.app.BrandMechanicBean;
import com.das.mechanic_base.bean.common.LocaleBean;
import com.das.mechanic_base.bean.main.HomeSetBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by chensi on 2018/3/6.
 */

public class X3StringUtils {

    private static Pattern p = Pattern.compile("1[0-9]{10}");
    /**
     * 判断手机号是否合法
     */
    public static boolean isPhone(String mobiles) {

        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    private static Pattern numPattern = Pattern.compile("^[-\\+]?[.\\d]*$");


    private static Pattern p1 = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z.*]{6,20}$");
    /**
     * 判断必须是否为密码类型
     */
    public static boolean isPassword(String str) {

        Matcher m = p1.matcher(str);
        return m.matches();
    }

    /**
     * 字符串 千位符
     *
     * @param num
     * @return
     */
    public static String num2thousand(String num) {
        String numStr = "";
        if (isEmpty(num)) {
            return numStr;
        }
        NumberFormat nf = NumberFormat.getInstance();
        try {
            DecimalFormat df = new DecimalFormat("#,###");
            numStr = df.format(nf.parse(num));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return numStr;
    }

    /**
     * 判断字符串是否可以转成数字
     *
     * @param str str
     * @return boolean
     */
    public static boolean isNum(String str) {
        if (null == str || "".equals(str)) {
            return false;
        }

        return numPattern.matcher(str).matches();
    }


    /**
     * 判断字符串是不是NULL或是空字符串,如果是，返回true，不是false
     *
     * @param str 待判断字符串
     * @return true/false
     */
    public static boolean isNullOrEmpty(final String str) {
        return str == null || "".equals(str);
    }

    /**
     * 拨打电话
     *
     * @param context
     * @param number
     */
    public static void call(Context context, String number) {
        context.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number)));
    }

    /**
     * 动态显示软键盘
     *
     * @param edit 必须是现实的edit
     */
    public static void showSoftInput(View edit) {
        InputMethodManager imm = (InputMethodManager) edit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            edit.requestFocus();
            imm.showSoftInput(edit, InputMethodManager.SHOW_FORCED);
        }
    }

    /**
     * 动态显示软键盘
     *
     * @param edit 必须是现实的edit
     */
    public static void hideSoftInput(View edit) {
        InputMethodManager imm = (InputMethodManager) edit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(edit.getWindowToken(),0);
        }
    }

    /**
     * 判断字符不能为空
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return TextUtils.isEmpty(str) || "".equals(str);
    }

    /**
     * 判断集合是否为空或者是否长度为0
     * @param list
     * @return
     */
    public static boolean isListEmpty(List list) {
        return list == null || list.size() == 0;
    }

    private static Pattern pattern = Pattern.compile("[0-9]*");

    /**
     * 判断字符串是否全是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        Matcher match = pattern.matcher(str);
        return match.matches();
    }

    /**
     * 判断字符串是否为小数或者数字
     * @param str
     * @return
     */
    public static boolean isAloneNum(String str) {
        return isInteger(str) || isDouble(str);
    }

    /**
     * 判断字符串是否是整数
     */
    public static boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断字符串是否是浮点数
     */
    public static boolean isDouble(String value) {
        try {
            Double.parseDouble(value);
            if (value.contains("."))
            {
                return true;
            }
            return false;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    // 时间 相减
    public static int minusNum(String[] startTime, String[] endTime) {
        int now = Integer.parseInt(startTime[0]) * 3600 + Integer.parseInt(startTime[1]) * 60;
        int end = Integer.parseInt(endTime[0]) * 3600 + Integer.parseInt(endTime[1]) * 60;
        if (now >= end) {
            return 0;
        }
        int i = end - now;
        return i / 60;
    }

    /**
     * 计算后台返回的时间与当前时间相差几天
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static int minusDay(String startTime, String endTime) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date d1;
        Date d2;
        try {
            d1 = df.parse(startTime);
            d2 = df.parse(endTime);

            long l = (d1.getTime() - d2.getTime()) / (60 * 60 * 1000 * 24);
            return (int) l;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return -1;
    }

    /**
     * 获取到当前时间
     *
     * @return
     */
    public static String getNowDateShort() {

        long time = System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.sql.Date d1 = new java.sql.Date(time);
        String t1 = format.format(d1);
        return t1;

    }

    private static Pattern pattern1 = Pattern.compile("^[\\u4E00-\\u9FFF]+$");

    /**
     * 判断输入的字符串是否为纯汉字
     *
     * @param str 传入的字符窜
     * @return 如果是纯汉字返回true, 否则返回false
     */
    public static boolean isChinese(String str) {

        return pattern1.matcher(str).matches();
    }

    // URL加密
    public static String encode(String str) {
        String encode = "";

        try {
            encode = URLEncoder.encode(str + "", "UTF-8");
            return encode;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    // URL解密
    public static String decode(String str) {
        String content = "";
        try {
            //content = URLDecoder.decode(str + "", "UTF-8");
            content = URLDecoder.decode(str.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            return content;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param dou double保留2位小数
     * @return
     */
    public static double doubleTo(double dou) {
        BigDecimal b = new BigDecimal(dou);
        return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    public static double doubleum(double dou,int i) {
        BigDecimal b = new BigDecimal(dou);
        return b.setScale(i, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    /**
     * double比较大小
     *
     * @return
     */
    public static boolean doubleComple(String strs) {
        BigDecimal data1 = new BigDecimal(strs);
        BigDecimal data2 = new BigDecimal("0.01");
        BigDecimal data3 = new BigDecimal("9999.99");
        int flag1 = data1.compareTo(data2);
        int flag2 = data1.compareTo(data3);
        return flag1 == -1 || flag2 == 1;
    }

    /**
     * double比较大小
     *
     * @return
     */
    public static boolean doubleComple(String strs, String str) {
        BigDecimal data1 = new BigDecimal(strs);
        BigDecimal data2 = new BigDecimal("0.01");
        BigDecimal data3 = new BigDecimal("99.99");
        int flag1 = data1.compareTo(data2);
        int flag2 = data1.compareTo(data3);
        return flag1 == -1 || flag2 == 1;
    }

    private static Pattern pattern3 = Pattern.compile("\t|\r|\n|\\s*");

    /**
     * 去除特殊字符 如换行
     *
     * @param src
     * @return
     */
    public static String replaceBlank(String src) {
        String dest = "";
        if (src != null) {

            Matcher matcher = pattern3.matcher(src);
            dest = matcher.replaceAll("");
        }
        return dest;
    }

    /**
     * 适配一下 后台返回图片地址的时候 有时候有http 有时候咩有
     *
     * @param str
     * @return
     */
    public static String getImageUrl(String str) {
        String headUrl = "";
        if (!X3StringUtils.isEmpty(str)) {
            // 不为空
            headUrl = str.contains("http") ? str : "http://" + str;
        }
        return headUrl;
    }

    /**
     * 根据当前月来选中样式
     *
     * @param month
     * @return
     */
    public static Point getSelcetPoint(int month) {
        if (month > 0 && month <= 5) {
            return new Point(month - 1, 0);
        } else if (month >= 6 && month <= 10) {
            return new Point(month - 6, 0);
        } else if (month >= 11 && month <= 12) {
            return new Point(month - 11, 2);
        }
        return null;
    }

    /**
     * 拼接集合里面的字符串，并用 、隔开
     *
     * @param list
     * @return
     */
    public static String getGoodsList(List<String> list) {
        if (list != null && list.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i));
                if (i < list.size() - 1) {
                    sb.append("\n");
                }
            }
            return sb.toString();
        } else {
            return "--";
        }
    }
    public static String getCarStyleList(List<String> list) {
        if (list != null && list.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i));
                if (i < list.size() - 1) {
                    sb.append("、");
                }
            }
            return sb.toString();
        } else {
            return "--";
        }


    }
    /**
     * 截取时间
     *
     * @param time
     * @return
     */
    public static String getSplit(String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 输入日期的格式
        SimpleDateFormat newDateFormat = new SimpleDateFormat("MM-dd HH:mm");
        Date date1 = null;
        try {
            date1 = simpleDateFormat.parse(time);

            return newDateFormat.format(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";

    }

    /**
     * 获取当前程序的版本号
     *
     * @param context
     * @return
     */
    public static String getAppVersion(Context context) {
        String version = "0";
        try {
            version = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 判断字符串是否全部由英文构成
     */
    public static boolean isEnglish(String name) {
        if (X3StringUtils.isEmpty(name)) {
            return false;
        }
        return name.matches("[a-zA-Z]+");
    }

    /**
     * Md5加密
     * @param sourceStr
     * @return
     */
    public static String MD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                {
                    i += 256;
                }
                if (i < 16)
                {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }
        return result;
    }

    public static int getInt(double number){
        BigDecimal bd=new BigDecimal(number).setScale(0, BigDecimal.ROUND_HALF_UP);
        return Integer.parseInt(bd.toString());
    }

    /**
     * 将double值处理一下 如果小数点后为0的话 那么将保留整数
     * @param d
     * @return
     */
    public static String formatDouble(double d) {
        BigDecimal bg = new BigDecimal(d).setScale(1, RoundingMode.UP);
        double num = bg.doubleValue();
        if (Math.round(num) - num == 0) {
            return String.valueOf((long) num);
        }
        return String.valueOf(num);
    }

    /**
     * 将double值处理一下
     * @param d
     * @return
     */
    public static String twoDouble(double d) {
        if (X3Constent.isChina()) {
            return formatTwoDouble(d);
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00", DecimalFormatSymbols.getInstance(Locale.CHINA));
        return decimalFormat.format(d);
    }

    /**
     * 将double值处理一下 如果小数点后为0的话 那么将保留整数
     * @param d
     * @return
     */
    public static String formatTwoDouble(double d) {
        BigDecimal bg = new BigDecimal(d).setScale(2, RoundingMode.UP);
        double num = bg.doubleValue();
        if ((int)num - num == 0) {
            return String.valueOf((int) num);
        }
        return String.valueOf(num);
    }

    public static boolean isEmojiCharacter(char codePoint) {
        return !((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD) || ((codePoint >= 0x20) && codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    /**
     * 获取assets下的常用姓氏集合
     * @param mContext
     * @return
     */
    public static List<String> getAssetsForUseName(Context mContext,String fileName) {
        StringBuilder newstringBuilder = new StringBuilder();
        InputStream inputStream = null;
        try {
            inputStream = mContext.getResources().getAssets().open(fileName);
            InputStreamReader isr = new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(isr);
            String jsonLine;
            while ((jsonLine = reader.readLine()) != null) {
                newstringBuilder.append(jsonLine);
            }
            reader.close();
            isr.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String result =  newstringBuilder.toString();
        Gson gson = new Gson();
        return gson.fromJson(result, new TypeToken<List<String>>() {
        }.getType());
    }

    /**
     * 获取创建接车单的性别
     * @param sex
     * @return
     */
    public static String getCreateUserSex(String sex) {
        String gender = "MALE";
        if (X3StringUtils.isEmpty(sex)) {
            return gender;
        }
        if ("女士".equals(sex) || "Mrs.".equals(sex) || "Ms.".equals(sex) || "Miss.".equals(sex) ||
            "Frau".equals(sex) || "Fräulein".equals(sex)) {
            return "FEMALE";
        }

        return gender;
    }

    /**
     * 获取首页展示的title集合
     * @param mContext
     * @return
     */
    public static List<HomeSetBean> getHomeSetTitleList(Context mContext,boolean receiveBase,boolean toDo) {
        List<HomeSetBean> mList = new ArrayList<>();
        if (receiveBase) {
            mList.add(new HomeSetBean(mContext.getString(R.string.x3_main_pick_work),mContext.getString(R.string.x3_close_home_service),receiveBase,0));

        }
//            mList.add(new HomeSetBean(mContext.getString(R.string.home_tab_book),mContext.getString(R.string.close_home_book),true,1));
        if (toDo) {
            mList.add(new HomeSetBean(mContext.getString(R.string.x3_todo_record),mContext.getString(R.string.x3_close_home_task),toDo,2));
        }

        return mList;
    }

    /**
     * 获取首页展示的title集合
     * @param mContext
     * @return
     */
    public static List<HomeSetBean> getHomeSetAllTitleList(Context mContext) {
        List<HomeSetBean> mList = new ArrayList<>();
        mList.add(new HomeSetBean(mContext.getString(R.string.x3_main_pick_work),mContext.getString(R.string.x3_close_home_service),true,0));
//      mList.add(new HomeSetBean(mContext.getString(R.string.home_tab_book),mContext.getString(R.string.close_home_book),true,1));
        mList.add(new HomeSetBean(mContext.getString(R.string.x3_todo_record),mContext.getString(R.string.x3_close_home_task),true,2));


        return mList;
    }

    private static String[] colorList = new String[]{"#C2B6FF","#7149FF","#FF4565","#FFA200","#FFD791"};

    /**
     * 获取检测的有效颜色
     * @param index
     * @return
     */
    public static int getDetectionColor(int index){
        if (index >= 5) {
            index = 0;
        }
        return Color.parseColor(colorList[index]);
    }

    /**
     * 下载远程文件
     */
    @SuppressLint("CheckResult")
    public static void downAppStringFile(Context mContext) {
        // 获取本地语言设置
        LocaleBean appLocale = LanguageUtiles.getAppLocale(mContext);
        if (!appLocale.isSave) {
            return;
        }

        NetWorkHttp.getLanguageApi()
                .getLanguageSet(appLocale.locale.getLanguage().toUpperCase() + "_" + appLocale.locale.getCountry().toUpperCase(),5)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<Map<String, Object>>() {
                    @Override
                    protected void onDone(Map<String, Object> map) {
                        X3MyApp.strMap = map;
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

    /**
     * 下载远程文件
     */
    public static void downAppStringFile(Context mContext,IOnDownLocaleCallback iOnDownLocaleCallback) {
        // 获取本地语言设置
        LocaleBean appLocale = LanguageUtiles.getAppLocale(mContext);
        if (!appLocale.isSave) {
            return;
        }
        NetWorkHttp.getLanguageApi()
                .getLanguageSet(appLocale.locale.getLanguage().toUpperCase() + "_" + appLocale.locale.getCountry().toUpperCase(),5)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<Map<String, Object>>() {
                    @Override
                    protected void onDone(Map<String, Object> map) {
                        X3MyApp.strMap = map;
                        if (iOnDownLocaleCallback != null) {
                            iOnDownLocaleCallback.iOnDownSuccess();
                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        if (iOnDownLocaleCallback != null) {
                            iOnDownLocaleCallback.iOnDownFailed();
                        }
                    }
                });

    }

    public interface IOnDownLocaleCallback{
        void iOnDownSuccess();

        void iOnDownFailed();
    }

    public static void showTextOther28Style(Context mContext,String beforeText, String allText, TextView tv_text) {

        SpannableString style_all_course = new SpannableString(allText);

        style_all_course.setSpan(new TextAppearanceSpan(mContext, R.style.before_28text_style), 0, beforeText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        style_all_course.setSpan(new TextAppearanceSpan(mContext, R.style.after_28text_style), beforeText.length(), style_all_course.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        tv_text.setText(style_all_course, TextView.BufferType.SPANNABLE);

    }

    /**
     * 获取技师端远程配置
     * @return
     */
    public static BrandMechanicBean getBrandMechanicBean() {
        String data = (String) SpHelper.getData(X3Constent.BRAND_MECHANIC_CONFIG, "");
        if (X3StringUtils.isEmpty(data)) {
            return null;
        }
        return new Gson().fromJson(data, BrandMechanicBean.class);
    }

    /**
     * 获取故障灯的图片
     * @param answer
     * @return
     */
    public static int getLightSpan(String answer) {
        String[] itemNames = answer.split("_");

        if (itemNames == null || itemNames.length < 2) {
            return 0;
        }

        switch (itemNames[0]) {
            case "1":
                return R.mipmap.x3_light_break_error;
            case "2":
                return R.mipmap.x3_light_warn;
            case "3":
                return R.mipmap.x3_light_oil_error;
            case "4":
                return R.mipmap.x3_light_battery_error;
            case "5":
                return R.mipmap.x3_light_abs_error;
            case "6":
                return R.mipmap.x3_light_engine_error;
            case "7":
                return R.mipmap.x3_light_water_error;
            case "8":
                return R.mipmap.x3_light_fuel_oil_error;
            case "9":
                return R.mipmap.x3_light_tyre_error;
            case "10":
                return R.mipmap.x3_light_safe_error;
            case "11":
                return R.mipmap.x3_light_glass_water_error;
            case "12":
                return R.mipmap.x3_light_turn_error;
            case "13":
                return R.mipmap.x3_light_esp_error;
            case "14":
                return R.mipmap.x3_light_epc_error;
            case "15":
                return R.mipmap.x3_others;
        }

        return 0;
    }

    /**
     * 求出最大公约数
     * @param molecular
     * @param denominator
     * @return
     */
    public static int getMaxCommon(int molecular,int denominator) {
        int a = molecular;
        int b = denominator;
        int temp;
        while (b != 0) {
            temp = a % b;
            a = b;
            b = temp;
        }
        return a;
    }

}
